//
//  String+Extension.swift
//  SwiftBaseProject
//
//  Created by 苏州巨细 on 2018/5/21.
//  Copyright © 2018年 苏州巨细. All rights reserved.
//

import UIKit
import CommonCrypto


extension String {
    
    /// 将字符串转成数组
    ///
    /// - Returns: Array<Any>
    func toArray() -> (Array<Any>) {
        
        if let jsonData = self.data(using: .utf8) {
            let arr = try? JSONSerialization.jsonObject(with: jsonData, options:.mutableContainers )
            
            if arr != nil {
                return arr as! Array
            }
            
        }
        return Array()
    }
    
    /// 将字符串转成字典
    ///
    /// - Returns: NSDictionary
    func toDictionary() ->(NSDictionary){
        
        let jsonData:Data = self.data(using: .utf8)!
        
        let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
        if dict != nil {
            return dict as! NSDictionary
        }
        return NSDictionary()
    }
    
    /// 将字符串进行URL编码
    ///
    /// - Returns: 编码后的字符串
    func toUrlEncoding() -> (String) {
        
        //需要包含的特殊字符
        let set = CharacterSet.init(charactersIn: "!*'();@&+$?%[]").inverted
        
        let encodeUrlString = self.addingPercentEncoding(withAllowedCharacters: set) ?? ""
        
        //        let encodeUrlString = self.addingPercentEncoding(withAllowedCharacters:.urlQueryAllowed) ?? ""
        return encodeUrlString
    }
    
    /// MD5加密
    ///
    /// - Returns: 加密文本
    func MD5() -> (String) {
        let str = self.cString(using: String.Encoding.utf8)
        let strLen = CC_LONG(self.lengthOfBytes(using: String.Encoding.utf8))
        let digestLen = Int(CC_MD5_DIGEST_LENGTH)
        let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
        
        CC_MD5(str!, strLen, result)
        
        let hash = NSMutableString()
        for i in 0 ..< digestLen {
            hash.appendFormat("%02x", result[i])
        }
        result.deinitialize(count: 1)
        
        return String(format: hash as String)
    }
    
    /// 返回第一次出现的指定子字符串在此字符串中的索引
    ///
    /// - Parameters:
    ///   - sub: 子类字符串
    ///   - backwards: 是否反向
    /// - Returns: 位置
    func positionOf(sub:String, backwards:Bool = false)->Int {
        var pos = -1
        if let range = range(of:sub, options: backwards ? .backwards : .literal ) {
            if !range.isEmpty {
                pos = self.distance(from:startIndex, to:range.lowerBound)
            }
        }
        return pos
    }
    
    /// 移除文本中的空格
    ///
    /// - Returns: 去除空格文本
    func removeSpaceString() -> (String) {
        
        let str = self.replacingOccurrences(of: " ", with: "")
        return str
    }
    
    /// 是否为空
    /// - Returns: 是否为空
    func isBlank() ->(Bool) {
        
        let str = removeSpaceString()
        if str.count <= 0 {
            return true
        }
        return false
    }
}


